// ignore_for_file: import_of_legacy_library_into_null_safe

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/hj_utils/screen.dart';

import '../../hj_model/splash/ads_model.dart';
import '../../routers/jump_router.dart';
import '../../tools_base/widget/net_image_widget.dart';

class SplashBannerWidget extends StatefulWidget {
  final List<AdsInfoModel> adData;
  final Color? backgroundColor;
  const SplashBannerWidget({Key? key, this.backgroundColor, required this.adData}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _SplashBannerWidgetState();
  }
}

class _SplashBannerWidgetState extends State<SplashBannerWidget> {
  List<AdsInfoModel> get _advertsList => widget.adData;
  late PageController _pageController;
  Timer? _timer;
  @override
  void initState() {
    super.initState();
    _pageController = PageController(initialPage: 0);
    _pageController.addListener(_listenerCallback);
    if (_advertsList.length > 1) {
      Future.delayed(Duration(seconds: 1)).then((value) {
        _timer = Timer.periodic(const Duration(milliseconds: 2500), _onTimer);
      });
    }
  }

  void _listenerCallback() {
    if (mounted) setState(() {});
  }

  void _onTimer(Timer timer) {
    int pageIndex = _pageController.page?.toInt() ?? 0;
    _pageController.animateToPage(pageIndex + 1, duration: const Duration(milliseconds: 500), curve: Curves.ease);
  }

  @override
  Widget build(BuildContext context) {
    if (_advertsList.isEmpty) return const SizedBox();
    return Container(
        color: widget.backgroundColor ?? const Color(0xff1b1b1b),
        child: Stack(
          fit: StackFit.expand,
          children: [
            PageView.builder(
              itemCount: 1000 + _advertsList.length * 100,
              controller: _pageController,
              allowImplicitScrolling: true,
              onPageChanged: (index) {
                setState(() {});
              },
              itemBuilder: (BuildContext context, int index) {
                int realIndex = index % (_advertsList.length);
                AdsInfoModel advertsInfo = _advertsList[realIndex];
                return GestureDetector(
                  onTap: () {
                    pushToPageByLink(advertsInfo.href ?? "", id: advertsInfo.id);
                  },
                  child: NetworkImageLoader(
                    imageUrl: advertsInfo.cover ?? "",
                    width: screen.screenWidth,
                    height: screen.screenHeight,
                    fit: BoxFit.cover,
                    placeHolderWidget: realIndex == 0
                        ? Image.asset(
                            "assets/images/launch/ic_splash_bg.webp",
                            fit: BoxFit.cover,
                            width: screen.screenWidth,
                            height: screen.screenHeight,
                          )
                        : null,
                  ),
                );
              },
            ),
            Positioned(
              bottom: 7,
              child: _buildIndicatorWidget(),
            ),
          ],
        ));
  }

  Widget _buildIndicatorWidget() {
    int curPageIndex = 0;
    if (_pageController.hasClients == true && _advertsList.isNotEmpty) {
      curPageIndex = ((_pageController.offset + 200.0) ~/ screen.screenWidth) % _advertsList.length;
    }
    int allCount = _advertsList.length;
    List<Widget> widgets = [];
    for (int i = 0; i < allCount; i++) {
      if (curPageIndex == i) {
        widgets.add(Container(
          margin: const EdgeInsets.all(5),
          child: Container(
            width: 25,
            height: 8,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8 / 2),
              color: AppColors.primaryHighColor.withOpacity(0.5),
            ),
          ),
        ));
      } else {
        widgets.add(Container(
          margin: const EdgeInsets.all(5),
          child: Container(
            width: 8,
            height: 8,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(8 / 2),
              color: Colors.white.withOpacity(0.5),
            ),
          ),
        ));
      }
    }
    return SizedBox(
      width: MediaQuery.of(context).size.width - 14 * 2,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: widgets,
      ),
    );
  }

  @override
  void dispose() {
    _timer?.cancel();
    _timer = null;
    _pageController.dispose();
    _pageController.removeListener(_listenerCallback);
    super.dispose();
  }
}
